package com.jx.driving.transform;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.jx.driving.protocol.terminal.codec.ClassReaderWriter;

/**
 * 
 * @author wuxiaozeng
 *
 */
public class DefaultTransform implements Transform {

	private Map<Class<?>, ClassReaderWriter> codec = new HashMap<>();

	@Override
	public byte[] transformObjectToByteArray(Object source) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			makesureCodec(source.getClass()).write(out, source);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return out.toByteArray();
	}

	@Override
	public <T> T transformToObject(InputStream in, Class<?> objectClass) {
		try {
			return (T) makesureCodec(objectClass).read(in);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	protected ClassReaderWriter makesureCodec(Class<?> clazz) throws Exception {
		ClassReaderWriter crw = codec.get(clazz);
		if (crw != null) {
			return crw;
		}
		crw = new ClassReaderWriter(clazz);
		codec.put(clazz, crw);
		return crw;
	}
}
